package com.codeanalysissys.backend.controller;

import com.codeanalysissys.backend.entity.Language;
import com.codeanalysissys.backend.entity.response.Result;
import com.codeanalysissys.backend.service.frame.FileService;
import com.codeanalysissys.backend.utils.CookieUtil;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;


@RestController
@RequestMapping("/files")
public class FileController {
    @Autowired
    private FileService fileService;

    public static final Integer SINGLE_GRAPH_RES = 0;
    public static final Integer SINGLE_DATA_RES = 1;
    public static final Integer JSONL_GRAPH_RES = 2;
    public static final Integer JSONL_DATA_RES = 3;

    @PostMapping("/upload")
    public Result uploadFile(@RequestParam("type") Integer type,
                             @RequestParam("lang") Language lang,
                             @RequestParam(value = "name", required = false) String name,
                             @RequestParam(value = "desc", required = false) String desc,
                             @RequestParam("file") MultipartFile file,
                             // 是否开启多线程
                             @RequestParam(value = "multiThread", required = false, defaultValue = "false") Boolean multiThread) {
        return fileService.analysisFile(type, lang, name, desc, file, multiThread);
    }

    @GetMapping("/get-result")
    public Result getResult(@RequestParam("fileId") String fileId) {
        return fileService.getAnalysisResult(fileId);
    }


    //    @PostMapping("/getAnalysisData")
//    public Result getAnalysisData(@RequestParam("fileId") String fileId) {
//
//    }
//


    /**
     * 导出 jsonl 分析图结果
     *
     * @param fileId 上传文件 Id
     * @return 文件流
     */
    @GetMapping("/export")
    public ResponseEntity<InputStreamResource> exportResult(@RequestParam("fileId") String fileId,
                                                            @RequestParam("exportType") Integer exportType,
                                                            @RequestParam(value = "exportFormat", required = false) String format) {
        String filePath = null;
        if (Objects.equals(exportType, JSONL_GRAPH_RES) || Objects.equals(exportType, JSONL_DATA_RES)) {
            filePath = fileService.getJSONLRes(fileId, exportType);
        } else if (Objects.equals(exportType, SINGLE_GRAPH_RES)) {
            // todo 获取单一语言源代码图结果路径
            filePath = fileService.getSingleGraphRes(fileId, format);
        } else if (Objects.equals(exportType, SINGLE_DATA_RES)) {
            // todo 获取单一语言源代码分析数据路径
            filePath = fileService.getSingleDataRes(fileId);
        } else {
            return ResponseEntity.badRequest().body(null);
        }
        if (filePath == null)
            return ResponseEntity.badRequest().body(null);

        // 获取本地文件流，封装为InputStreamResource对象
        File file = new File(filePath);
        if (!file.exists() || file.length() == 0) {
            return ResponseEntity.badRequest().body(null);
        }

        InputStream inputStream;
        try {
            inputStream = new FileInputStream(file);
        } catch (IOException e) {
            return ResponseEntity.badRequest().body(null);
        }
        InputStreamResource resource = new InputStreamResource(inputStream);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        // 在浏览器中以附件形式返回，而不是直接打开
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getName());
//        headers.add(HttpHeaders.CONTENT_TYPE, "'application/octet-stream'");

        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(resource);
    }

}
